package com.smart.translator.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import androidx.core.content.ContextCompat;

/**
 * 离线TTS引擎
 * 提供多种朗读方案，确保在没有TTS引擎的设备上也能工作
 */
public class OfflineTtsEngine {
    private static final String TAG = "OfflineTtsEngine";
    
    private Context context;
    private TextToSpeech tts;
    private eSpeakTtsEngine espeakEngine;
    private AudioManager audioManager;
    private ExecutorService executor;
    private Handler mainHandler;
    private boolean isInitialized = false;
    private boolean isEspeakAvailable = false;
    
    public interface TtsCallback {
        void onSuccess(String text);
        void onError(String text, String error);
        void onFallback(String text);
    }
    
    public OfflineTtsEngine(Context context) {
        this.context = context;
        this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        this.executor = Executors.newSingleThreadExecutor();
        this.mainHandler = new Handler(Looper.getMainLooper());
        
        initTts();
    }
    
    /**
     * 初始化TTS
     */
    private void initTts() {
        try {
            // 首先尝试初始化eSpeak引擎
            initEspeakEngine();
            
            // 然后初始化系统TTS作为备用
            initSystemTts();
            
        } catch (Exception e) {
            Log.e(TAG, "TTS初始化异常", e);
            isInitialized = false;
        }
    }
    
    /**
     * 初始化eSpeak引擎
     */
    private void initEspeakEngine() {
        try {
            espeakEngine = new eSpeakTtsEngine(context);
            isEspeakAvailable = true;
            Log.d(TAG, "eSpeak引擎初始化成功");
        } catch (Exception e) {
            Log.w(TAG, "eSpeak引擎初始化失败，将使用系统TTS", e);
            isEspeakAvailable = false;
        }
    }
    
    /**
     * 初始化系统TTS
     */
    private void initSystemTts() {
        try {
            tts = new TextToSpeech(context, status -> {
                if (status == TextToSpeech.SUCCESS) {
                    // 尝试设置中文
                    int result = tts.setLanguage(Locale.CHINESE);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.w(TAG, "中文不可用，使用默认语言");
                        tts.setLanguage(Locale.getDefault());
                    }
                    
                    tts.setPitch(1.0f);
                    tts.setSpeechRate(1.0f);
                    isInitialized = true;
                    Log.d(TAG, "系统TTS初始化成功");
                } else {
                    Log.e(TAG, "系统TTS初始化失败: " + status);
                    isInitialized = false;
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "系统TTS初始化异常", e);
            isInitialized = false;
        }
    }
    
    /**
     * 朗读文本
     */
    public void speak(String text, TtsCallback callback) {
        if (text == null || text.trim().isEmpty()) {
            if (callback != null) {
                callback.onError(text, "文本为空");
            }
            return;
        }
        
        executor.execute(() -> {
            // 设置音频输出到扬声器
            setupAudioOutput();
            
            // 优先使用eSpeak引擎
            if (isEspeakAvailable && espeakEngine != null && espeakEngine.isInitialized()) {
                Log.d(TAG, "使用eSpeak引擎朗读: " + text);
                espeakEngine.speak(text, new eSpeakTtsEngine.TtsCallback() {
                    @Override
                    public void onSuccess(String text) {
                        Log.d(TAG, "eSpeak朗读成功: " + text);
                        if (callback != null) {
                            mainHandler.post(() -> callback.onSuccess(text));
                        }
                    }
                    
                    @Override
                    public void onError(String text, String error) {
                        Log.w(TAG, "eSpeak朗读失败，尝试系统TTS: " + error);
                        // eSpeak失败，尝试系统TTS
                        trySystemTts(text, callback);
                    }
                    
                    @Override
                    public void onFallback(String text) {
                        Log.w(TAG, "eSpeak使用备用方案，尝试系统TTS");
                        // eSpeak使用备用方案，尝试系统TTS
                        trySystemTts(text, callback);
                    }
                });
            } else {
                // eSpeak不可用，直接尝试系统TTS
                Log.d(TAG, "eSpeak不可用，尝试系统TTS");
                trySystemTts(text, callback);
            }
        });
    }
    
    /**
     * 尝试使用系统TTS
     */
    private void trySystemTts(String text, TtsCallback callback) {
        if (isInitialized && tts != null) {
            try {
                int result = tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, "system_tts");
                if (result == TextToSpeech.SUCCESS) {
                    Log.d(TAG, "系统TTS朗读成功: " + text);
                    if (callback != null) {
                        mainHandler.post(() -> callback.onSuccess(text));
                    }
                } else {
                    Log.w(TAG, "系统TTS朗读失败，使用备用方案");
                    useFallbackMethod(text, callback);
                }
            } catch (Exception e) {
                Log.e(TAG, "系统TTS朗读异常", e);
                useFallbackMethod(text, callback);
            }
        } else {
            Log.w(TAG, "系统TTS未初始化，使用备用方案");
            useFallbackMethod(text, callback);
        }
    }
    
    /**
     * 设置音频输出到扬声器
     */
    private void setupAudioOutput() {
        try {
            if (audioManager != null) {
                audioManager.setMode(AudioManager.MODE_NORMAL);
                audioManager.setSpeakerphoneOn(true);
                
                // 设置音量到最大
                int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
                
                Log.d(TAG, "音频输出设置完成");
            }
        } catch (Exception e) {
            Log.e(TAG, "设置音频输出失败", e);
        }
    }
    
    /**
     * 使用备用朗读方法
     */
    private void useFallbackMethod(String text, TtsCallback callback) {
        try {
            // 1. 振动反馈（检查权限）
            if (hasVibratePermission()) {
                android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                if (vibrator != null && vibrator.hasVibrator()) {
                    vibrator.vibrate(100);
                    Log.d(TAG, "振动反馈已执行");
                }
            } else {
                Log.w(TAG, "缺少振动权限，跳过振动反馈");
            }
            
            // 2. 播放提示音
            playBeepSound();
            
            // 3. 通知回调
            if (callback != null) {
                mainHandler.post(() -> callback.onFallback(text));
            }
            
            Log.i(TAG, "备用朗读完成: " + text);
            
        } catch (Exception e) {
            Log.e(TAG, "备用朗读失败", e);
            if (callback != null) {
                mainHandler.post(() -> callback.onError(text, e.getMessage()));
            }
        }
    }
    
    /**
     * 检查是否有振动权限
     */
    private boolean hasVibratePermission() {
        return ContextCompat.checkSelfPermission(context, android.Manifest.permission.VIBRATE) 
               == PackageManager.PERMISSION_GRANTED;
    }
    
    /**
     * 播放提示音
     */
    private void playBeepSound() {
        try {
            android.media.ToneGenerator toneGen = new android.media.ToneGenerator(AudioManager.STREAM_MUSIC, 100);
            toneGen.startTone(android.media.ToneGenerator.TONE_PROP_BEEP, 200);
            
            mainHandler.postDelayed(() -> {
                try {
                    toneGen.release();
                } catch (Exception e) {
                    Log.e(TAG, "释放ToneGenerator失败", e);
                }
            }, 300);
            
            Log.d(TAG, "提示音播放完成");
        } catch (Exception e) {
            Log.e(TAG, "播放提示音失败", e);
        }
    }
    
    /**
     * 停止朗读
     */
    public void stop() {
        if (tts != null && isInitialized) {
            tts.stop();
        }
        if (espeakEngine != null) {
            espeakEngine.stop();
        }
    }
    
    /**
     * 释放资源
     */
    public void release() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
            tts = null;
        }
        
        if (espeakEngine != null) {
            espeakEngine.release();
            espeakEngine = null;
        }
        
        if (executor != null) {
            executor.shutdown();
        }
        
        isInitialized = false;
        isEspeakAvailable = false;
        Log.d(TAG, "OfflineTtsEngine已释放");
    }
    
    /**
     * 检查是否已初始化
     */
    public boolean isInitialized() {
        return isInitialized || isEspeakAvailable;
    }
    
    /**
     * 检查eSpeak是否可用
     */
    public boolean isEspeakAvailable() {
        return isEspeakAvailable && espeakEngine != null && espeakEngine.isInitialized();
    }
} 